package month1;


public class ReverseNodesInKGroup25_04 {
    public static void main(String[] args) {
        System.out.println(reverseKGroup(new ListNode(new int[]{1, 2, 3, 4, 5, 6, 7}), 5));
    }

    /**
     * 迭代
     *
     * @param head
     * @param k
     * @return
     */
    static ListNode reverseKGroup(ListNode head, int k) {
        if (k == 1) {
            return head;
        }
        ListNode ret = null;
        int i = 0;
        for (ListNode node = head, pre = null; node != null; ++i) {
            int n = k;
            ListNode tmp = node;
            while (--n > 0 && node.next != null) {
                node = node.next;
            }
            if (i == 0) {
                ret = node;
            }
            if (n == 0) {
                ListNode next = node.next;
                node.next = null;
                reverse(tmp);
                if (pre != null) {
                    pre.next = node;
                }
                pre = tmp;
                node = next;
            } else {
                // k <= n 所以不为空
                pre.next = tmp;
                node = null;
            }
        }
        return ret;
    }

    static ListNode reverse(ListNode node) {
        ListNode ret = null;
        while (node != null) {
            ListNode next = node.next;
            node.next = ret;
            ret = node;
            node = next;
        }
        return ret;
    }
}
